package zb.blog.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zb.blog.base.bean.Result;
import zb.blog.base.global.GlobalVar;
import zb.blog.base.sessionScope.SessionScope;
import zb.blog.base.util.EncryptUtil;
import zb.blog.base.util.StringUtil;
import zb.blog.base.util.TimeUtil;
import zb.blog.bean.CommentBean;
import zb.blog.dao.CommentDao;
import zb.blog.service.ICommentService;
import zb.blog.service.IVerificationCode;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentService implements ICommentService {
    @Autowired
    private IVerificationCode iVerificationCode;
    @Autowired
    private CommentDao commentDao;

    @Override
    public Result addComment(Map<String, String> param, HttpSession session) {
        Result r = new Result();
        int status = iVerificationCode.validateCode(session, param);
        if (status != 1) {
            r.setSuccess(GlobalVar.FAIL);
            r.setMsg("验证码失效！");
            return r;
        }
        if (param.get("doc_type") != null && param.get("doc_type").equals("2")) {
            param.put("id", GlobalVar.MESSAGE_ID);//给留言添加id。默认是2
        }
        if (param.get("id") == null || param.get("id").length() <= 0) {
            r.setSuccess(GlobalVar.FAIL);
            r.setMsg("参数错误，评论失败！");
            return r;
        }

        param.put("parent_Id", "0");//顶级节点
        param.put("header_img", "/static/img/defaultHeader.jpg");//默认头像
        param.put("ip", StringUtil.getIpAddr(SessionScope.getHttpServletRequest()));//获取ip地址
        param.put("audit_status", "0");//待审核
        try {
            param.put("id", EncryptUtil.customDecrypt(param.get("id")).toString());
            String type = param.get("os_type");
            if (type != null && type.equals("PC")) {
                String version = param.get("version");
                if (version != null && version.indexOf(".") > 0) {
                    version = version.substring(0, version.indexOf("."));
                }
                param.put("Browser", param.get("browser") + " " + version + "," + param.get("OS"));
            } else if (type != null && type.equals("Mobile")) {
                String OS = param.get("OS") == null ? "" : param.get("OS");
                String version = param.get("version") == null ? "" : param.get("version");
                String mobile = param.get("mobile") == null ? "" : param.get("mobile");
                String browser = OS + " " + version + "," + mobile;//Android 7.0,mi4C
                if (param.get("iPad") != null && param.get("iPad").equals("1")) {
                    browser += ",iPad";
                }
                if (param.get("qq") != null && param.get("qq").equals("1")) {
                    browser += ",QQ";
                } else if (param.get("weixin") != null && param.get("weixin").equals("1")) {
                    browser += ",微信";
                }
                param.put("Browser", browser);
            }
            commentDao.addComment(param);
            Map<String, String> resDataMap = new HashMap<>();
            resDataMap.put("osv", param.get("Browser"));
            resDataMap.put("defaultHeader", GlobalVar.QNY_DEFAULT_HEADER_IMG);
            r.setMsg("您的评论会在审核之后显示在评论列表！");
            r.setSuccess(GlobalVar.SUCCESS);
            r.setData(resDataMap);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            r.setSuccess(GlobalVar.FAIL);
            r.setMsg("添加失败！");
            return r;
        }

    }

    @Override
    public Map<String, Object> getCommentByArticleId(int pageNum, Integer pageSize, String id, Integer type) {
        if (type != null && type == 2) {
            id = GlobalVar.MESSAGE_ID;//  id 其实是 2
        }
        if (id == null || id.length() <= 0) {
            return null;
        }
        Map<String, Object> resMap = new HashMap<>();
        try {
            if (pageSize == null) {
                pageSize = GlobalVar.COMM_PAGE_SIZE;//默认每次加载5条
            }
            PageHelper.startPage(pageNum, pageSize);
            Integer audit_status = 1;//审核状态
            List<CommentBean> list = commentDao.getCommentByArticleId(EncryptUtil.customDecrypt(id), audit_status);
            PageInfo<CommentBean> pageInfo = new PageInfo<>(list);
            //进行一对多查询分页数据不对，我们只要总条数和是否是最后一页即可
            long total = pageInfo.getTotal();
            boolean isLastPage = pageInfo.isIsLastPage();
            List<Map<String, Object>> commentTreeList = new ArrayList<>();
            for (CommentBean commentBean : list) {
                Map<String, Object> commentMap = new HashMap<>();
                int pId = commentBean.getId();
                commentBean.setCreate_time(TimeUtil.timeToDiff(commentBean.getCreate_time(), false));
                List<CommentBean> subList = commentDao.getCommentByPId(pId, 1);
                subList = subList.stream().map(x -> {
                    x.setCreate_time(TimeUtil.timeToDiff(x.getCreate_time(), false));
                    return x;
                }).collect(Collectors.toList());
                commentMap.put("parentComment", commentBean);
                commentMap.put("subComment", subList);
                commentTreeList.add(commentMap);
            }
            resMap.put("total", total);
            resMap.put("isLastPage", isLastPage);
            resMap.put("list", commentTreeList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap;
    }
}
